package test2;


import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author liule
 * @date 2023/8/7 14:37
 * @Desc : 测试https :配置httpclient绕过https安全认证
 */
public class HttpClientTest5_SSL {
    public static void main(String[] args) throws Exception {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", trustHttpsCertificates())
                .build();
        // 创建一个HttpClientConnectionManager
        PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(registry);
        //定制CloseableHttpClient
        HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(pool);
        // httpClientBuilder构建HttpClient对象
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        String urlstr = "https://www.baidu.com/";

        HttpGet httpGet = new HttpGet(urlstr);
        // 可关闭的响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpGet);
            // 代表本次请求的成功失败的状态
            StatusLine statusLine = response.getStatusLine();
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                HttpEntity entity = response.getEntity();
                Header contentType = entity.getContentType();
                System.out.println("contentType:" + contentType);
                //对HttpEntity操作的工具类
                String toStringSesult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringSesult);
                // 确保流关闭
                EntityUtils.consume(entity);
            } else {
                System.out.println("响应失败，响应码：" + statusLine.getStatusCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }

    }

    // 创建支持安全协议的链接工厂
    private static ConnectionSocketFactory trustHttpsCertificates() throws Exception {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
            // 判断是否信任url
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });
        SSLContext sslcontext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new
                SSLConnectionSocketFactory(sslcontext,
                new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"},
                null, NoopHostnameVerifier.INSTANCE);
        return sslConnectionSocketFactory;


    }
}
